//
//  HomeViewController.swift
//  DSWeiBo
//
//  Created by 刘星 on 16/7/23.
//  Copyright © 2016年 LiuXing. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

let cellIdentifier = "homeCell"
class HomeViewController: BaseViewController {
    // MARK:- 属性
    private lazy var titleButton: TitleButton = {
        let titleButton = TitleButton()
        return titleButton
    }()
    /// 微博数组
    private lazy var viewModels: [StatusViewModel] = {
        let viewModels = [StatusViewModel]()
        return viewModels
    }()
    private lazy var tipLabel: UILabel = {
        let tipLabel = UILabel()
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.mainScreen().bounds.width, height: 32)
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(14)
        tipLabel.textAlignment = .Center
        return tipLabel
    }()
    // MARK:- 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载动画
        visitorView.addRotationAnmianl()
        // 没有登录
        if !isLogin {
            return
        }
        // 设置导航栏
        setNavigationBar()
        
//        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.estimatedRowHeight = 200
        
        // 请求数据
//        loadStatuses()
        // 上啦刷新Header
        setTableViewHeader()
        setFootViewHeader()
        setupTipLabel()
    }
}

// MARK:- 设置导航栏UI界面
extension HomeViewController {
    private func setNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        titleButton.setTitle("LiuXing", forState: .Normal)
        titleButton.addTarget(self, action: #selector(HomeViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleButton
    }
    private func setTableViewHeader() {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatuses))
        header.setTitle("下拉刷新", forState: .Idle)
        header.setTitle("释放更新", forState: .Pulling)
        header.setTitle("下拉刷新", forState: .Idle)
        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    private func setFootViewHeader() {
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatuses))
    }
    private func setupTipLabel() {
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        tipLabel.hidden = true
    }
}
// MARK:- 事件监听的函数
extension HomeViewController {
    @objc private func titleBtnClick(titleBtn : TitleButton) {
        titleBtn.selected = !titleBtn.selected
    }
}
// MARK:- 请求数据
extension HomeViewController {
    // 加载新数据
    @objc private func loadNewStatuses() {
        loadStatuses(true)
    }
    /// 上拉
    @objc private func loadMoreStatuses() {
        loadStatuses(false)
    }
    private func loadStatuses(isNewData: Bool) {
        // 获取since_id
        var since_id = 0
        var max_id = 0
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        } else {
            max_id = viewModels.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        NetWorkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (result, error) in
            if error != nil {
                print(error)
                return
            }
            guard let resultArray = result else {
                return
            }
            var tempViewModel = [StatusViewModel]()
            for statusDict in resultArray {
                let status = Status(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempViewModel.append(viewModel)
            }
            if isNewData {
                self.viewModels = tempViewModel + self.viewModels
            } else {
                self.viewModels += tempViewModel
            }
            self.cacheImages(tempViewModel)
        }
    }
    private func cacheImages(viewModels : [StatusViewModel]) {
        // 0.创建group
        let group = dispatch_group_create()
        
        // 1.缓存图片
        for viewmodel in viewModels {
            for picURL in viewmodel.picURLs {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(picURL, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 2.刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            self.showTipLabel(viewModels.count)
        }
    }
    /// 显示提示的Label
    private func showTipLabel(count : Int) {
        // 1.设置tipLabel的属性
        tipLabel.hidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条新微博"
        
        // 2.执行动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
        }) { (_) -> Void in
            UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: { () -> Void in
                self.tipLabel.frame.origin.y = 10
                }, completion: { (_) -> Void in
                    self.tipLabel.hidden = true
            })
        }
    }
}
// MARK: - tableView
extension HomeViewController {
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let viewModel = viewModels[indexPath.row]
        return viewModel.cellHeigth
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModels.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! HomeViewCell
        let viewModel = viewModels[indexPath.row]
        cell.viewModel = viewModel
        return cell
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}